package com.zuipin.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.zuipin.entity.BasePayOnlineTool;
import com.zuipin.entity.Member;
import com.zuipin.entity.PayOrder;
import com.zuipin.entity.ThirdAccount;
import com.zuipin.enums.PayMethod;
import com.zuipin.framework.annotation.Valid;
import com.zuipin.framework.annotation.Valids;
import com.zuipin.framework.emuns.ErrorCode;
import com.zuipin.framework.exception.CustomException;
import com.zuipin.framework.result.Result;
import com.zuipin.service.IBasePayOnlineToolService;
import com.zuipin.service.IMemberService;
import com.zuipin.service.IPayOrderService;
import com.zuipin.service.IThirdAccountService;
import com.zuipin.util.AliPayUtil;
import com.zuipin.util.ArithUtil;
import com.zuipin.util.CommonUtils;
import com.zuipin.util.Pkipair;
import com.zuipin.util.RegexUtils;
import com.zuipin.util.StringUtil;
import com.zuipin.util.WechatUtil;
import com.zuipin.vo.ModityOrderUseStore;
import com.zuipin.vo.PayOrderVo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import springfox.documentation.annotations.ApiIgnore;

/*
 * @ApiParam(name = "srcSystemId", value = "来源系统", required = true) @RequestParam Long srcSystemId,
 * @ApiParam(name = "orderRemark", value = "订单备注", required = true) @RequestParam String orderRemark,
 * @ApiParam(name = "freightSum", value = "运费", required = true) @RequestParam BigDecimal freightSum,
 * @ApiParam(name = "useJfSum", value = "使用的积分", required = true) @RequestParam Integer useJfSum,
 * @ApiParam(name = "useCashBackSum", value = "使用的返现", required = true) @RequestParam BigDecimal useCashBackSum,
 * @ApiParam(name = "orderSum", value = "// 付款总额+运费（实际支付）", required = true) @RequestParam BigDecimal orderSum,
 * @ApiParam(name = "productPaySum", value = "商品价", required = true) @RequestParam BigDecimal productPaySum,
 * @ApiParam(name = "totalWeight", value = "运费", required = true) @RequestParam BigDecimal totalWeight,
 * @ApiParam(name = "buyerId", value = "卖家ID", required = true) @RequestParam Long buyerId,
 * @ApiParam(name = "isPayOnline", value = "是否在线支付", required = true) @RequestParam Short isPayOnline,
 * @ApiParam(name = "useRedPacketId", value = "使用的红包Id", required = false) @RequestParam Long useRedPacketId,
 * @ApiParam(name = "useRedPacketSum", value = "使用的红包金额", required = true) @RequestParam BigDecimal useRedPacketSum,
 * @ApiParam(name = "useRebateSum", value = "使用的返佣", required = true) @RequestParam BigDecimal useRebateSum,
 * @ApiParam(name = "useStoreValue", value = "使用的充值", required = true) @RequestParam BigDecimal useStoreValue,
 * @ApiParam(name = "isBrushOrder", value = "是否刷单", required = false) @RequestParam Short isBrushOrder
 */
/**
 * @description :
 * @author : xujinding
 * @date : 2017年3月24日 下午1:48:19
 */
@Api(value = "付款单-xujinding", description = "付款单-xujinding")
@Controller
@RequestMapping(value = "/payOrder")
public class PayOrderController {
	@Resource
	private IBasePayOnlineToolService	basePayOnlineToolService;
	@Resource
	private IPayOrderService			payOrderService;
	@Resource
	private IMemberService				memberService;
	@Resource
	private IThirdAccountService		thirdAccountService;
	
	private Logger						log						= Logger.getLogger(PayOrderController.class);
	
	/** 更新订单状态锁 */
	private static byte[]				UP_ORDER_STATUS_LOCK	= new byte[0];
	// 快钱支付url
	public static String				QK_PAY_URL				= "https://www.99bill.com/gateway/recvMerchantInfoAction.htm";
	public static String				WECHAT_CODE				= "pay_by_wechat";
	public static String				ALIPAY_CODE				= "pay_by_alipay";
	public static Long					THRID_PLAT_WECHAT		= 49L;
	
	@ResponseBody
	@RequestMapping(value = "/findPayOrderById", method = RequestMethod.POST)
	@ApiOperation(notes = "根据ID查询付款单", value = "根据ID查询付款单")
	@ApiIgnore
	public Result<PayOrder> findPayOrderById(@ApiParam(name = "payId", value = "付款单Id", required = true) @RequestParam(required = true) Long payId) {
		Result<PayOrder> result = new Result<PayOrder>();
		PayOrder po = payOrderService.findPayOrderById(payId);
		result.setErrorCode(ErrorCode.SUCCESS);
		result.setData(po);
		return result;
	}
	
	/**
	 * @Description:确认支付
	 * @Title:
	 * @author: xujinding
	 * @throws ParseException 
	 * @throws CustomException 
	 * @date: 2017年3月27日上午9:30:29
	 */
	@Valids({ @Valid(name = "payMethod", required = true, regex = "ALIPAY|WECHAT|BALANCE_PAY|BANK_PAY|FAST_MONEY"), })
	@ResponseBody
	@RequestMapping(value = "/confirmPay", method = RequestMethod.POST)
	@ApiOperation(notes = "确认支付ALIPAY|WECHAT|BALANCE_PAY|BANK_PAY|FAST_MONEY", value = "确认支付ALIPAY|WECHAT|BALANCE_PAY|BANK_PAY|FAST_MONEY")
	public Result confirmPay(@ApiParam(name = "payId", value = "付款单Id", required = true) @RequestParam(required = true) Long payId,
			@ApiParam(name = "payMethod", value = "付款方式ALIPAY|WECHAT|BALANCE_PAY|BANK_PAY", required = true) @RequestParam(required = true) String payMethod,
			@ApiParam(name = "sysUserId", value = "操作人的Id", required = true) @RequestParam(required = true) Long sysUserId) throws CustomException {
		Result res = new Result();
		// 获取用户
		res = payOrderService.updateToPay(payId, sysUserId, res, payMethod);
		return res;
	}
	
	/**
	 * @Description:删除付款单
	 * @Title:
	 * @author: xujinding
	 * @throws CustomException 
	 * @date: 2017年3月27日上午9:30:29
	 */
	
	@ResponseBody
	@RequestMapping(value = "/deletePay", method = RequestMethod.POST)
	@ApiOperation(notes = "删除付款单", value = "删除付款单")
	public Result deletePay(@ApiParam(name = "payId", value = "付款单Id", required = true) @RequestParam(required = true) Long payId) throws CustomException {
		Result res = new Result();
		// 获取用户
		res = payOrderService.deleteToPay(payId, res);
		return res;
	}
	
	/**
	 * @Description:通知成功支付（微信，支付宝）
	 * @Title:
	 * @author: xujinding
	 * @date: 2017年3月27日上午9:30:29
	 */
	@Valids({ @Valid(name = "payMethod", required = true, regex = "ALIPAY|WECHAT|FAST_MONEY"), @Valid(name = "amount", required = true), })
	@ResponseBody
	@RequestMapping(value = "/noticePaySuccess", method = RequestMethod.POST)
	@ApiOperation(notes = "通知成功支付（ALIPAY|WECHAT|FAST_MONEY）", value = "（ALIPAY|WECHAT|FAST_MONEY）")
	public Result noticePaySuccess(@ApiParam(name = "payNo", value = "付款单No（payOrderId_邮费版本号）", required = true) @RequestParam(required = true) String payNo,
			@ApiParam(name = "payMethod", value = "支付方式，(ALIPAY|WECHAT|FAST_MONEY)", required = true) @RequestParam(required = true) String payMethod,
			@ApiParam(name = "amount", value = "支付金额（单位）", required = true) @RequestParam(required = true) String amount,
			@ApiParam(name = "returnParams", value = "第三方返回参数）", required = true) @RequestParam(required = true) String returnParams) {
		// synchronized (UP_ORDER_STATUS_LOCK) {
		Result res = new Result();
		log.info("第三方支付成功--回调修改状态--start");
		
		// 获取支付方式
		res = payOrderService.updatePayState(payNo, amount, returnParams, payMethod);
		
		log.info("第三方支付成功--回调修改状态--end");
		// }
		return res;
	}
	
	/**
	 * 支付回调错误日志保存
	* @Description:
	* @Title: 
	* @author: xujinding
	* @date: 2017年4月22日下午4:58:58
	 */
	@Valids({ @Valid(name = "payMethod", required = true, regex = "WECHAT|ALIPAY"), @Valid(name = "amount", required = true),
			@Valid(name = "remark", required = true, maxLength = 100), })
	@ResponseBody
	@RequestMapping(value = "/savePayLog", method = RequestMethod.POST)
	@ApiOperation(notes = "支付回调错误保存日志", value = "支付回调错误保存日志")
	public Result savePayLog(@ApiParam(name = "payNo", value = "付款单No（payOrderId_邮费版本号）", required = true) @RequestParam(required = true) String payNo,
			@ApiParam(name = "payMethod", value = "支付方式，ALIPAY|WECHAT", required = true) @RequestParam(required = true) String payMethod,
			@ApiParam(name = "amount", value = "支付金额（单位）", required = true) @RequestParam(required = true) String amount,
			@ApiParam(name = "returnParams", value = "第三方返回参数）", required = true) @RequestParam(required = true) String returnParams,
			@ApiParam(name = "remark", value = "备注", required = true) @RequestParam(required = true) String remark) {
		Result res = new Result();
		payOrderService.savePayLog(payMethod, new BigDecimal(amount), payOrderService.getPayId(payNo), remark, returnParams);
		res.setErrorCode(ErrorCode.SUCCESS);
		
		return res;
	}
	
	/**
	 * 微信支付
	* @Description:
	* @Title: 
	* @author: xujinding
	 * @throws CustomException 
	 * @throws UnsupportedEncodingException 
	 * @throws NoSuchAlgorithmException 
	 * @throws Exception 
	* @date: 2017年4月10日上午11:26:15
	 */
	@Valids({ @Valid(name = "ip", required = true, regex = RegexUtils.IP), @Valid(name = "tradeType", required = true, regex = "JSAPI|NATIVE"), })
	@ResponseBody
	@RequestMapping(value = "/wxPay", method = RequestMethod.POST)
	@ApiOperation(notes = "微信支付-统一下单接口（公众号信息通过付款单号来自哪个系统调用基础数据获得）", value = "微信支付-统一下单接口（公众号信息通过付款单号来自哪个系统调用基础数据获得）")
	public Result wxPay(HttpServletRequest request, @ApiParam(name = "payId", value = "付款单Id", required = true) @RequestParam(required = true) Long payId,
			@ApiParam(name = "ip", value = "ip", required = true) @RequestParam(required = true) String ip,
			@ApiParam(name = "tradeType", value = "交易类型，JSAPI|NATIVE", required = true) @RequestParam(required = true) String tradeType)
			throws NoSuchAlgorithmException, UnsupportedEncodingException, CustomException {
		Result res = new Result();
		if (payId != null) {
			PayOrder payOrder = payOrderService.findPayOrderById(payId);
			if (payOrder != null && PayOrder.NO.equals(payOrder.getPayStatus())) {
				ThirdAccount thirdAccount = thirdAccountService.findByMemberId(payOrder.getCreateMemberId(), THRID_PLAT_WECHAT, payOrder.getSysId());
				if (thirdAccount != null) {
					String openId = thirdAccount.getOpenId();
					String payNo = payOrder.getId() + "_" + payOrder.getVersionFreight();// not null, 商户订单号、、订单号+_+邮费版本号
					BasePayOnlineTool payTool = basePayOnlineToolService.findBySysIdAndCode(WECHAT_CODE, payOrder.getSysId());
					if (payTool == null || StringUtil.isEmpty(payTool.getNotifyUrl()) || StringUtil.isEmpty(payTool.getAppId()) || StringUtil.isEmpty(payTool.getAppSecret())
							|| StringUtil.isEmpty(payTool.getMchId()) || StringUtil.isEmpty(payTool.getKeyValue())) {
						res.setErrorCode(ErrorCode.ORDER_ERRPR);
						res.setMessage("请检查微信的基础数据！");
						return res;
					}
					Map<String, String> toolMap = new HashMap<String, String>();
					toolMap.put("notifyUrl", payTool.getNotifyUrl());
					toolMap.put("returnUrl", payTool.getReturnUrl());
					toolMap.put("appId", payTool.getAppId());
					toolMap.put("appSecret", payTool.getAppSecret());
					toolMap.put("keyValue", payTool.getKeyValue());
					toolMap.put("mchId", payTool.getMchId());
					JSONObject jsobj = WechatUtil.callUnifiedOrder(payOrder.getOrderSum().doubleValue(), payNo, openId, ip, "order", toolMap, tradeType);
					if (jsobj == null) {
						res.setErrorCode(ErrorCode.ORDER_ERRPR);
						res.setMessage("统一下单失败");
					} else {
						res.setData(jsobj);
						res.setErrorCode(ErrorCode.SUCCESS);
					}
				} else {
					log.error("thirdAccount为空");
					res.setErrorCode(ErrorCode.ORDER_ERRPR);
					res.setMessage("thirdAccount is null");
					
				}
			} else {
				res.setErrorCode(ErrorCode.ORDER_ERRPR);
				res.setMessage("payId为" + payId + "查询不到或者已支付");
			}
		} else {
			res.setErrorCode(ErrorCode.ORDER_ERRPR);
			res.setMessage("payId为空");
		}
		
		return res;
	}
	
	/**
	 * 微信订单异步回调接口
	 * 
	 * @Title: pay
	 * @author xujinding
	 * @date 2016年4月05日 下午2:30:26
	 * @return
	 * @return Result
	 * @throws IOException
	 * @throws ParseException
	 */
	@RequestMapping(value = "/wechatNotice", method = RequestMethod.POST)
	@ApiOperation(notes = "微信订单异步回调接口", value = "微信订单异步回调接口")
	@ApiIgnore
	public void wechatNotice(HttpServletRequest request, HttpServletResponse response) throws IOException, ParseException {
		java.io.BufferedReader bis = new java.io.BufferedReader(new java.io.InputStreamReader(request.getInputStream()));
		String line = null;
		String result = "";
		try {
			while ((line = bis.readLine()) != null) {
				result += line + "\r\n";
			}
		} catch (Exception e) {
			log.error(e.getMessage());
		} finally {
			bis.close();
		}
		// 判断返回值
		if (result != null && !"".equals(result.trim())) {
			JSONObject jsOb = JSONObject.parseObject(WechatUtil.xml2JSON(result).toString());
			if (jsOb != null) {
				String returnCode = jsOb.getString("return_code");
				if (returnCode != null && "SUCCESS".equals(returnCode)) {
					String resultCode = jsOb.getString("result_code");
					if (resultCode != null && "SUCCESS".equals(resultCode)) {
						String payNo = jsOb.getString("out_trade_no");// 订单号
						String cashFee = jsOb.getString("cash_fee");// 支付金额
						
						String realPay = String.valueOf(ArithUtil.div(new BigDecimal(cashFee), new BigDecimal(100)));
						if (payNo != null) {
							synchronized (UP_ORDER_STATUS_LOCK) {
								log.info("微信支付成功--回调修改状态--start");
								payOrderService.updatePayState(payNo, realPay, result, PayMethod.WECHAT + "");
								log.info("微信支付成功--回调修改状态--end");
							}
						}
					}
				}
			}
		}
		response.getWriter().write("SUCCESS");
	}
	
	/**
	 * 支付宝支付
	* @Description:
	* @Title: 
	* @author: xujinding
	* @date: 2017年4月10日上午11:26:15
	 */
	@ResponseBody
	@RequestMapping(value = "/aliPay", method = RequestMethod.POST)
	@ApiOperation(notes = "支付宝支付（支付宝信息通过付款单号来自哪个系统调用基础数据获得）", value = "支付宝-统一下单接口（公众号信息通过付款单号来自哪个系统调用基础数据获得）")
	public Result aliPay(@ApiParam(name = "payId", value = "付款单Id", required = true) @RequestParam(required = true) Long payId)
			throws UnsupportedEncodingException, NoSuchAlgorithmException {
		Result res = new Result();
		if (payId != null) {
			PayOrder payOrder = payOrderService.findPayOrderById(payId);
			if (payOrder != null && PayOrder.NO.equals(payOrder.getPayStatus())) {
				BasePayOnlineTool payTool = basePayOnlineToolService.findBySysIdAndCode(ALIPAY_CODE, payOrder.getSysId());
				if (payTool == null || StringUtil.isEmpty(payTool.getNotifyUrl()) || StringUtil.isEmpty(payTool.getReturnUrl()) || StringUtil.isEmpty(payTool.getAppId())
						|| StringUtil.isEmpty(payTool.getPartner()) || StringUtil.isEmpty(payTool.getSellerId()) || StringUtil.isEmpty(payTool.getPrivateKey())
						|| StringUtil.isEmpty(payTool.getPublicKey()) || StringUtil.isEmpty(payTool.getKeyValue())) {
					res.setErrorCode(ErrorCode.ORDER_ERRPR);
					res.setMessage("请检查支付宝的基础数据！");
					return res;
				}
				Map<String, String> toolMap = new HashMap<String, String>();
				toolMap.put("notifyUrl", payTool.getNotifyUrl());
				toolMap.put("returnUrl", payTool.getReturnUrl());
				toolMap.put("appId", payTool.getAppId());
				// toolMap.put("appSecret", payTool.getAppSecret());
				toolMap.put("keyValue", payTool.getKeyValue());
				toolMap.put("privateKey", payTool.getPrivateKey());
				toolMap.put("publicKey", payTool.getPublicKey());
				// toolMap.put("showUrl", payTool.getMchId());
				toolMap.put("partner", payTool.getPartner());
				toolMap.put("sellerId", payTool.getSellerId());
				String out_trade_no = payOrder.getId() + "_" + payOrder.getVersionFreight();// not null, 商户订单号、、订单号+_+邮费版本号
				String htmlStr = AliPayUtil.bulidAliForm("product", String.valueOf(payOrder.getOrderSum()), out_trade_no, out_trade_no, toolMap);
				res.setData(htmlStr);
				res.setErrorCode(ErrorCode.SUCCESS);
				
			} else {
				log.info("payId为" + payId + "查询不到或者已支付");
				res.setErrorCode(ErrorCode.ORDER_ERRPR);
				res.setMessage("payId为" + payId + "查询不到或者已支付");
			}
		} else {
			res.setErrorCode(ErrorCode.ORDER_ERRPR);
			res.setMessage("payId为空");
		}
		return res;
	}
	
	/**
	 * 支付宝异步回调
	* @Description:
	* @Title: 
	* @author: xujinding
	 * @throws IOException 
	* @date: 2017年4月6日下午3:21:08
	 */
	@RequestMapping(value = "/aliNotice", method = RequestMethod.POST)
	@ApiOperation(notes = "支付宝订单异步回调接口", value = "支付宝订单异步回调接口")
	@ApiIgnore
	@ResponseBody
	public String aliNotice(HttpServletRequest request, HttpServletResponse response) throws NoSuchAlgorithmException, IOException {
		log.info("aliNotice begin ...");
		Map<String, String> params = new HashMap<String, String>();
		Map<?, ?> requestParams = request.getParameterMap();
		for (Iterator<?> iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
			}
			// 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			valueStr = new String(valueStr.getBytes("UTF-8"));
			params.put(name, valueStr);
		}
		
		// 获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
		// 商户订单号
		String out_trade_nos = new String(request.getParameter("out_trade_no").getBytes("UTF-8"));
		
		// 支付宝交易号
		// String trade_no = new String(request.getParameter("trade_no").getBytes("UTF-8"));
		// 交易状态
		String trade_status = new String(request.getParameter("trade_status").getBytes("UTF-8"));
		System.out.println(trade_status + "#########################");
		String v_amount = new String(request.getParameter("total_fee").getBytes("UTF-8"));
		// 获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
		
		// 计算得出通知验证结果(理论不会为空，不做判断，除非该数据，，因为在支付前有做判断)
		Long payId = getPayId(out_trade_nos);
		PayOrder payOrder = payOrderService.findPayOrderById(payId);
		BasePayOnlineTool payTool = basePayOnlineToolService.findBySysIdAndCode(ALIPAY_CODE, payOrder.getSysId());
		boolean verify_result = AliPayUtil.verify(params, payTool.getPublicKey(), payTool.getKeyValue());
		// String remark = "";
		if (verify_result) {// 验证成功
			log.info("验证成功 ...");
			log.info("trade_status=" + trade_status);
			// ——请根据您的业务逻辑来编写程序
			if (trade_status.equals("TRADE_FINISHED") || trade_status.equals("TRADE_SUCCESS")) {
				// 判断该笔订单是否在商户网站中已经做过处理
				// 如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
				// 如果有做过处理，不执行商户的业务程序
				log.info("支付成功--回调修改状态--start");
				payOrderService.updatePayState(out_trade_nos, v_amount, params.toString(), PayMethod.ALIPAY + "");
				log.info("支付成功--回调修改状态--end");
			}
		} else {
			log.info("PayNo为" + out_trade_nos + "::签名验证失败！");
			payOrderService.savePayLog("", new BigDecimal(v_amount), payOrderService.getPayId(out_trade_nos), "payNo::" + out_trade_nos + "==签名验证失败!", out_trade_nos.toString());
		}
		log.info("aliNoticeReturn end ...");
		// response.getWriter().write();
		return "success";
	}
	
	public Long getPayId(String payNo) {
		Long payId = null;
		if (payNo != null) {
			if (payNo.indexOf("_") != -1) {
				// 去掉版本号
				String[] payStr = payNo.split("_");
				payId = Long.valueOf(payStr[0]);
			} else {
				payId = Long.valueOf(payNo);
			}
		}
		return payId;
	}
	
	/**
	 * 
	* @Description:支付宝同步回调接口
	* @Title: 
	* @author: xujinding
	* @date: 2017年4月6日下午3:25:17
	 */
	@RequestMapping(value = "/aliReturn", method = RequestMethod.POST)
	@ApiOperation(notes = "支付宝同步回调接口", value = "支付宝订单异步回调接口")
	@ApiIgnore
	public Result aliReturn(HttpServletRequest request) throws UnsupportedEncodingException {
		System.out.println("回调成功");
		return null;
	}
	
	/**
	 * 快钱支付
	* @Description:  bankType  要与bankCard_开头  并且后面接银行编码详情见快钱文档，可以不传 默认全部
	* @Title: 
	* @author: xujinding
	* @date: 2017年4月7日上午8:56:47
	 */
	@RequestMapping(value = "/buildQKPay", method = RequestMethod.POST)
	@ApiOperation(notes = "快钱支付", value = "快钱支付")
	@ResponseBody
	@ApiIgnore
	public Result buildQKPay(HttpServletRequest request,
			@ApiParam(name = "bankType", value = "银行卡-- 要与bankCard_开头  并且后面接银行编码详情见快钱文档（或参考cbt）", required = false) @RequestParam(required = false) String bankType,
			@ApiParam(name = "payId", value = "付款单Id", required = true) @RequestParam(required = true) Long payId) {
		Result res = new Result();
		// bgUrl/merchantAcctId换掉
		if (payId != null) {
			PayOrder payOrder = payOrderService.findPayOrderById(payId);
			if (payOrder != null && PayOrder.NO.equals(payOrder.getPayStatus())) {
				Member member = memberService.findById(payOrder.getCreateId());
				if (member != null) {
					String inputCharset = "1";// not null, 字符集， 固定选择值：1、2、3; 1代表UTF-8; 2代表GBK; 3代表GB2312
					String pageUrl = ""; // 接叐支付结果的页面地址
					String bgUrl = "http://otest.oteao.com:3533/payOrder/qkSunccessReturn";// 服务器接叐支付结果的后台地址
					String version = "v2.0"; // not null, 网关版本, 固定值：v2.0 注意为小写字母
					String language = "1";// not null, 网关页面显示诧言种类, 固定值：1 1代表中文显示
					String signType = "4";// not null, 签名类型, 4代表DSA戒者RSA签名方式
					// <!-- 买卖双方信息参数 -->
					String merchantAcctId = "1002347809701";// not null, 人民币账号， 数字串 本参数用来挃定接收款项的人民币账号,
					String payerName = payOrder.getCreateId() + ""; // userId;// 支付人姓名
					// String payerIdType = "";// 指定付款人
					// String payerId = ""; // order.getUserId();// 付款人标识
					// String payerIP = "";// 付款人IP
					// <!-- 业务参数 -->
					String payerContactType = "2";// 支付人联系方式类型, 固定值：1或者2； 1代表电子邮件方式；2代表手机联系方式
					String payerContact = member.getPhone();// 支付人联系方式, 字符串 根据payerContactType的方式填写对庒字符，邮箱戒者手机号码
					String orderId = payOrder.getId() + "_" + payOrder.getVersionFreight();// not null, 商户订单号、、订单号+_+邮费版本号
					String money = "";// not null, 商户订单金额
					if (StringUtil.isBlank(money)) {
						money = "0.00";
					}
					String orderAmount = String.valueOf(ArithUtil.mul(payOrder.getOrderSum(), new BigDecimal(100)).intValue());
					String orderTime = new java.text.SimpleDateFormat("yyyyMMddHHmmss")// not null, 商户订单提交时间
							.format(new java.util.Date());
					// String orderTimestamp = "";// 快钱时间戳
					String productName = "";// 商品名称
					String productNum = "";// 商品数量
					String productId = "";// 商品代码
					String productDesc = "";// 商品描述
					String ext1 = "";// 扩展字段1
					String ext2 = "";// 扩展字段2
					String bankId = "";
					String payType = "00";// not null, 支付方式
					if (null != bankType && !"".equals(bankType)) {
						String[] s = bankType.split("_");
						// 网银，银行卡
						if ("bankCard".equals(s[0])) {
							payType = "10";
							bankId = s[1];
						}
					}
					// String cardIssuer = "";// 发卡机构
					// String cardNum = "";// 卡号
					// String remitType = "";// 线下汇款类型
					// String remitCode = ""; // 汇款识别码
					String redoFlag = "";// 同一订单禁止重复提交标志
					String pid = "";// 合作伙伴在快钱的用户编号
					// String submitType = "";// 提交方式
					// String orderTimeOut = ""; // 交易超时时间
					// String extDataType = "";// 附加信息类型
					// String extDataContent = "";// 附加信息
					// <!-- 商户交易参考信息参数（不包含在报文加签中） -->
					// String referDataType = "";// 参考交易信息类型
					// String referData = "";// 参考交易信息
					String signMsgVal = "";
					signMsgVal = appendParam(signMsgVal, "inputCharset", inputCharset);
					signMsgVal = appendParam(signMsgVal, "pageUrl", pageUrl);
					signMsgVal = appendParam(signMsgVal, "bgUrl", bgUrl);
					signMsgVal = appendParam(signMsgVal, "version", version);
					signMsgVal = appendParam(signMsgVal, "language", language);
					signMsgVal = appendParam(signMsgVal, "signType", signType);
					signMsgVal = appendParam(signMsgVal, "merchantAcctId", merchantAcctId);
					signMsgVal = appendParam(signMsgVal, "payerName", payerName);
					signMsgVal = appendParam(signMsgVal, "payerContactType", payerContactType);
					signMsgVal = appendParam(signMsgVal, "payerContact", payerContact);
					signMsgVal = appendParam(signMsgVal, "orderId", orderId);
					signMsgVal = appendParam(signMsgVal, "orderAmount", orderAmount);
					signMsgVal = appendParam(signMsgVal, "orderTime", orderTime);
					signMsgVal = appendParam(signMsgVal, "productName", productName);
					signMsgVal = appendParam(signMsgVal, "productNum", productNum);
					signMsgVal = appendParam(signMsgVal, "productId", productId);
					signMsgVal = appendParam(signMsgVal, "productDesc", productDesc);
					signMsgVal = appendParam(signMsgVal, "ext1", ext1);
					signMsgVal = appendParam(signMsgVal, "ext2", ext2);
					signMsgVal = appendParam(signMsgVal, "payType", payType);
					signMsgVal = appendParam(signMsgVal, "bankId", bankId);
					signMsgVal = appendParam(signMsgVal, "redoFlag", redoFlag);
					signMsgVal = appendParam(signMsgVal, "pid", pid);
					// Pkipair pki = new Pkipair();
					String signMsg = Pkipair.signMsg(signMsgVal);
					Map<String, String> qkmap = new HashMap<String, String>();
					qkmap.put("signMsg", signMsg);
					qkmap.put("inputCharset", inputCharset);
					qkmap.put("pageUrl", pageUrl);
					qkmap.put("bgUrl", bgUrl);
					qkmap.put("version", version);
					qkmap.put("language", language);
					qkmap.put("signType", signType);
					qkmap.put("merchantAcctId", merchantAcctId);
					qkmap.put("payerName", payerName);
					qkmap.put("payerContactType", payerContactType);
					qkmap.put("payerContact", payerContact);
					// qkmap.put("payerIdType", payerIdType);
					// qkmap.put("payerId", payerId);
					// qkmap.put("payerIP", payerIP);
					qkmap.put("orderId", orderId);
					qkmap.put("orderAmount", orderAmount);
					qkmap.put("orderTime", orderTime);
					// qkmap.put("orderTimestamp", orderTimestamp);
					qkmap.put("productName", productName);
					qkmap.put("productNum", productNum);
					qkmap.put("productId", productId);
					qkmap.put("productDesc", productDesc);
					qkmap.put("ext1", ext1);
					qkmap.put("ext2", ext2);
					qkmap.put("payType", payType);
					qkmap.put("bankId", bankId);
					// qkmap.put("cardIssuer", cardIssuer);
					// qkmap.put("cardNum", cardNum);
					// qkmap.put("remitType", remitType);
					// qkmap.put("remitCode", remitCode);
					qkmap.put("redoFlag", redoFlag);
					qkmap.put("pid", pid);
					// qkmap.put("submitType", submitType);
					// qkmap.put("orderTimeOut", orderTimeOut);
					// qkmap.put("extDataType", extDataType);
					// qkmap.put("extDataContent", extDataContent);
					// qkmap.put("referDataType", remitType);
					// qkmap.put("referData", remitCode);
					// 构造HTML代码
					String htmlStr = CommonUtils.buildRequestHtml(qkmap, "post", "提交到快钱", QK_PAY_URL);
					System.out.println(htmlStr);
					log.info("快钱支付：：" + htmlStr);
					// request.setAttribute("htmlStr", htmlStr);
					// return "payapi";
					res.setData(htmlStr);
					res.setErrorCode(ErrorCode.SUCCESS);
				} else {
					log.info("memberId为" + payOrder.getCreateId() + "查无会员");
					
					res.setErrorCode(ErrorCode.ORDER_ERRPR);
					res.setMessage("memberId为" + payOrder.getCreateId() + "查无会员");
				}
			} else {
				log.info("payId为" + payId + "查询不到或者已支付");
				
				res.setErrorCode(ErrorCode.ORDER_ERRPR);
				res.setMessage("payId为" + payId + "查询不到或者已支付");
			}
		} else {
			
			res.setErrorCode(ErrorCode.ORDER_ERRPR);
			res.setMessage("payId为空");
		}
		return res;
	}
	
	/**
	 * 
	* @Description:快钱回调接口---使用get（快钱使用get回调）  rtnUrl要换
	* @Title: 
	* @author: xujinding
	* @date: 2017年4月6日下午3:25:17
	 */
	@RequestMapping(value = "/qkSunccessReturn", method = RequestMethod.GET)
	@ApiOperation(notes = "快钱回调接口", value = "快钱回调接口")
	@ApiIgnore
	@ResponseBody
	public String qkSunccessReturn(HttpServletRequest request) throws UnsupportedEncodingException {
		// 人民币网关账号，该账号为11位人民币网关商户编号+01,该值与提交时相同。
		String merchantAcctId = request.getParameter("merchantAcctId");
		// 网关版本，固定值：v2.0,该值与提交时相同。
		String version = request.getParameter("version");
		// 语言种类，1代表中文显示，2代表英文显示。默认为1,该值与提交时相同。
		String language = request.getParameter("language");
		// 签名类型,该值为4，代表PKI加密方式,该值与提交时相同。
		String signType = request.getParameter("signType");
		// 支付方式，一般为00，代表所有的支付方式。如果是银行直连商户，该值为10,该值与提交时相同。
		String payType = request.getParameter("payType");
		// 银行代码，如果payType为00，该值为空；如果payType为10,该值与提交时相同。
		String bankId = request.getParameter("bankId");
		// 商户订单号，该值与提交时相同。
		// ********注意版本号问题
		String orderId = request.getParameter("orderId");
		System.out.println("回调的订单号" + orderId);
		// 订单提交时间，格式：yyyyMMddHHmmss，如：20071117020101,该值与提交时相同。
		String orderTime = request.getParameter("orderTime");
		// 订单金额，金额以“分”为单位，商户测试以1分测试即可，切勿以大金额测试,该值与支付时相同。
		String orderAmount = request.getParameter("orderAmount");
		// 快钱交易号，商户每一笔交易都会在快钱生成一个交易号。
		String dealId = request.getParameter("dealId");
		// 银行交易号 ，快钱交易在银行支付时对应的交易号，如果不是通过银行卡支付，则为空
		String bankDealId = request.getParameter("bankDealId");
		// 快钱交易时间，快钱对交易进行处理的时间,格式：yyyyMMddHHmmss，如：20071117020101
		String dealTime = request.getParameter("dealTime");
		// 商户实际支付金额 以分为单位。比方10元，提交时金额应为1000。该金额代表商户快钱账户最终收到的金额。
		String payAmount = request.getParameter("payAmount");
		/*if (payAmount != null && !"".equals(payAmount)) {
			Double d = Double.parseDouble(payAmount) / 100;
			DecimalFormat df = new DecimalFormat("0.00");
			v_amount = df.format(d);
		}*/
		// 费用，快钱收取商户的手续费，单位为分。
		String fee = request.getParameter("fee");
		// 扩展字段1，该值与提交时相同。
		String ext1 = request.getParameter("ext1");
		// 扩展字段2，该值与提交时相同。
		String ext2 = request.getParameter("ext2");
		// 处理结果， 10支付成功，11 支付失败，00订单申请成功，01 订单申请失败
		String payResult = request.getParameter("payResult");
		payResult = payResult != null ? payResult.trim() : "";
		// 错误代码 ，请参照《人民币网关接口文档》最后部分的详细解释。
		String errCode = request.getParameter("errCode");
		// 签名字符串
		String signMsg = request.getParameter("signMsg");
		String merchantSignMsgVal = "";
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "merchantAcctId", merchantAcctId);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "version", version);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "language", language);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "signType", signType);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "payType", payType);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "bankId", bankId);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "orderId", orderId);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "orderTime", orderTime);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "orderAmount", orderAmount);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "dealId", dealId);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "bankDealId", bankDealId);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "dealTime", dealTime);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "payAmount", payAmount);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "fee", fee);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "ext1", ext1);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "ext2", ext2);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "payResult", payResult);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "errCode", errCode);
		
		System.out.println("签名字符串为： " + merchantSignMsgVal);
		Pkipair pki = new Pkipair();
		boolean flag = pki.enCodeByCer(merchantSignMsgVal, signMsg);
		
		int rtnOK = 0;
		String rtnUrl = "qkShowSuccess";
		
		PayOrder payOrder = payOrderService.findPayOrderById(payOrderService.getPayId(orderId));
		
		BigDecimal d = ArithUtil.mul(payOrder.getOrderSum(), new BigDecimal(100));
		int v_money = d.intValue();
		// 如果银行实际支付的金额不等于订单中的实际金额，那么显示失败
		if (Integer.parseInt(orderAmount) != v_money) {
			rtnUrl = "qkShowFail";
		}
		// 2 分转成元
		BigDecimal realPay = ArithUtil.div(new BigDecimal(payAmount), new BigDecimal(100));
		if (flag) {
			System.out.println("通过签名验证！");
			log.info("PayNo为" + orderId + "::通过签名验证！");
			switch (Integer.parseInt(payResult)) {
				case 10:
					log.info("支付成功--回调修改状态--start");
					//// 1、修改订单状态 带有版本号orderId
					boolean moditySuccess = false;
					payOrderService.updatePayState(orderId, realPay.toString(), merchantSignMsgVal, "");
					// 支付结果说明
					rtnOK = 1;
					// 以下是我们快钱设置的show页面，商户需要自己定义该页面。
					if (moditySuccess) {
						rtnUrl = rtnUrl + "?msg=success";
					} else {
						rtnUrl = rtnUrl + "?msg=false";
					}
					log.info("支付成功--回调修改状态--end");
					break;
				default:
					log.info("PayNo为" + orderId + "快钱返回支付状态：失败!");
					payOrderService.savePayLog("", realPay, payOrderService.getPayId(orderId), "快钱返回支付状态：失败!", merchantSignMsgVal);
					rtnOK = 1;
					// 以下是我们快钱设置的show页面，商户需要自己定义该页面。
					rtnUrl = rtnUrl + "?msg=false";
					break;
			}
		} else {
			log.info("PayNo为" + orderId + "::签名验证失败！");
			payOrderService.savePayLog("", realPay, payOrderService.getPayId(orderId), "payNo::" + orderId + "==签名验证失败!", merchantSignMsgVal);
			rtnOK = 1;
			// 以下是我们快钱设置的show页面，商户需要自己定义该页面。
			rtnUrl = rtnUrl + "?msg=error";
		}
		
		rtnUrl = "http://oteao.com";
		log.info("要显示的页面地址为（qkShow*）： " + rtnUrl);
		// 快钱要求这样返回
		String returnStr = "<result>" + rtnOK + "</result><redirecturl>" + rtnUrl + "</redirecturl>";
		
		return returnStr;
	}
	
	/*		#快钱 start
	qkKeyPwd=123456
	inputCharset=1
	bgUrl=http://xy.oteao.com/zuipin/pay.bank.qkReturn.jhtml
	qkShowSuccess=http://xy.oteao.com/zuipin/pay.bank.qkShow.jhtml
	qkShowFail=http://xy.oteao.com/zuipin/pay.bank.qkShowFail.jhtml
	rechargeBgUrl=http://xy.oteao.com/zuipin/pay.bank.qkRechargeReturn.jhtml
	qkRechargeShowSuccess=http://xy.oteao.com/zuipin/pay.bank.qkRechargeShow.jhtml
	qkRechargeShowFail=http://xy.oteao.com/zuipin/pay.bank.qkRechargeShowFail.jhtml
	version=v2.0
	language=1
	signType=4
	merchantAcctId=1002347809701*/
	
	/**
	 * 快钱字符串拼接
	* @Description:
	* @Title: 
	* @author: xujinding
	* @date: 2017年4月7日上午8:57:58
	 */
	public String appendParam(String returns, String paramId, String paramValue) {
		if (!"".equals(returns)) {
			if (!"".equals(paramValue)) {
				returns += "&" + paramId + "=" + paramValue;
			}
		} else {
			if (!"".equals(paramValue)) {
				returns = paramId + "=" + paramValue;
			}
		}
		return returns;
	}
	
	/**
	 * 
	* @Description:测试返回页面
	* @Title: 
	* @author: xujinding
	* @date: 2017年4月7日下午5:54:50
	 */
	@ApiIgnore
	@RequestMapping(value = "/helloJsp1", method = RequestMethod.GET)
	public String helloJsp() {
		System.out.println("12134567");
		return "success";
	}
	
	/**
	 * 
	* @Description:测试返回页面
	* @Title: 
	* @author: xujinding
	* @date: 2017年4月7日下午5:54:50
	 */
	@ApiIgnore
	@RequestMapping(value = "/wxpay")
	public String wxpay() {
		System.out.println("12134567");
		return "wxpay";
	}
	
	/**
	 * 快钱支付
	* @Description:  bankType  要与bankCard_开头  并且后面接银行编码详情见快钱文档，可以不传 默认全部
	* @Title: 
	* @author: xujinding
	* @date: 2017年4月7日上午8:56:47
	 */
	@RequestMapping(value = "/buildQKPayTest", method = RequestMethod.GET)
	@ApiOperation(notes = "快钱支付", value = "快钱支付")
	@ApiIgnore
	public String buildQKPayTest(HttpServletRequest request) {
		Result res = new Result();
		Long payId = 22L; // bankType处理
		String bankType = "bankCard_CMB";//
		// bgUrl/merchantAcctId换掉
		if (payId != null) {
			PayOrder payOrder = payOrderService.findPayOrderById(payId);
			if (payOrder != null && PayOrder.NO.equals(payOrder.getPayStatus())) {
				Member member = memberService.findById(payOrder.getCreateId());
				if (member != null) {
					String inputCharset = "1";// not null, 字符集， 固定选择值：1、2、3; 1代表UTF-8; 2代表GBK; 3代表GB2312
					String pageUrl = ""; // 接叐支付结果的页面地址
					String bgUrl = "http://otest.oteao.com:3533/payOrder/qkSunccessReturn";// 服务器接叐支付结果的后台地址
					String version = "v2.0"; // not null, 网关版本, 固定值：v2.0 注意为小写字母
					String language = "1";// not null, 网关页面显示诧言种类, 固定值：1 1代表中文显示
					String signType = "4";// not null, 签名类型, 4代表DSA戒者RSA签名方式
					// <!-- 买卖双方信息参数 -->
					String merchantAcctId = "1002347809701";// not null, 人民币账号， 数字串 本参数用来挃定接收款项的人民币账号,
					String payerName = payOrder.getCreateId() + ""; // userId;// 支付人姓名
					String payerIdType = "";// 指定付款人
					String payerId = ""; // order.getUserId();// 付款人标识
					String payerIP = "";// 付款人IP
					// <!-- 业务参数 -->
					String payerContactType = "2";// 支付人联系方式类型, 固定值：1或者2； 1代表电子邮件方式；2代表手机联系方式
					String payerContact = member.getPhone();// 支付人联系方式, 字符串 根据payerContactType的方式填写对庒字符，邮箱戒者手机号码
					String orderId = payOrder.getId() + "_" + payOrder.getVersionFreight();// not null, 商户订单号、、订单号+_+邮费版本号
					String money = "";// not null, 商户订单金额
					if (StringUtil.isBlank(money)) {
						money = "0.00";
					}
					String orderAmount = String.valueOf(ArithUtil.mul(payOrder.getOrderSum(), new BigDecimal(100)).intValue());
					String orderTime = new java.text.SimpleDateFormat("yyyyMMddHHmmss")// not null, 商户订单提交时间
							.format(new java.util.Date());
					String orderTimestamp = "";// 快钱时间戳
					String productName = "";// 商品名称
					String productNum = "";// 商品数量
					String productId = "";// 商品代码
					String productDesc = "";// 商品描述
					String ext1 = "";// 扩展字段1
					String ext2 = "";// 扩展字段2
					String bankId = "";
					String payType = "00";// not null, 支付方式
					if (null != bankType && !"".equals(bankType)) {
						String[] s = bankType.split("_");
						// 网银，银行卡
						if ("bankCard".equals(s[0])) {
							payType = "10";
							bankId = s[1];
						}
					}
					String cardIssuer = "";// 发卡机构
					String cardNum = "";// 卡号
					String remitType = "";// 线下汇款类型
					String remitCode = ""; // 汇款识别码
					String redoFlag = "";// 同一订单禁止重复提交标志
					String pid = "";// 合作伙伴在快钱的用户编号
					String submitType = "";// 提交方式
					String orderTimeOut = ""; // 交易超时时间
					String extDataType = "";// 附加信息类型
					String extDataContent = "";// 附加信息
					// <!-- 商户交易参考信息参数（不包含在报文加签中） -->
					String referDataType = "";// 参考交易信息类型
					String referData = "";// 参考交易信息
					String signMsgVal = "";
					signMsgVal = appendParam(signMsgVal, "inputCharset", inputCharset);
					signMsgVal = appendParam(signMsgVal, "pageUrl", pageUrl);
					signMsgVal = appendParam(signMsgVal, "bgUrl", bgUrl);
					signMsgVal = appendParam(signMsgVal, "version", version);
					signMsgVal = appendParam(signMsgVal, "language", language);
					signMsgVal = appendParam(signMsgVal, "signType", signType);
					signMsgVal = appendParam(signMsgVal, "merchantAcctId", merchantAcctId);
					signMsgVal = appendParam(signMsgVal, "payerName", payerName);
					signMsgVal = appendParam(signMsgVal, "payerContactType", payerContactType);
					signMsgVal = appendParam(signMsgVal, "payerContact", payerContact);
					signMsgVal = appendParam(signMsgVal, "orderId", orderId);
					signMsgVal = appendParam(signMsgVal, "orderAmount", orderAmount);
					signMsgVal = appendParam(signMsgVal, "orderTime", orderTime);
					signMsgVal = appendParam(signMsgVal, "productName", productName);
					signMsgVal = appendParam(signMsgVal, "productNum", productNum);
					signMsgVal = appendParam(signMsgVal, "productId", productId);
					signMsgVal = appendParam(signMsgVal, "productDesc", productDesc);
					signMsgVal = appendParam(signMsgVal, "ext1", ext1);
					signMsgVal = appendParam(signMsgVal, "ext2", ext2);
					signMsgVal = appendParam(signMsgVal, "payType", payType);
					signMsgVal = appendParam(signMsgVal, "bankId", bankId);
					signMsgVal = appendParam(signMsgVal, "redoFlag", redoFlag);
					signMsgVal = appendParam(signMsgVal, "pid", pid);
					// Pkipair pki = new Pkipair();
					String signMsg = Pkipair.signMsg(signMsgVal);
					Map<String, String> qkmap = new HashMap<String, String>();
					qkmap.put("signMsg", signMsg);
					qkmap.put("inputCharset", inputCharset);
					qkmap.put("pageUrl", pageUrl);
					qkmap.put("bgUrl", bgUrl);
					qkmap.put("version", version);
					qkmap.put("language", language);
					qkmap.put("signType", signType);
					qkmap.put("merchantAcctId", merchantAcctId);
					qkmap.put("payerName", payerName);
					qkmap.put("payerContactType", payerContactType);
					qkmap.put("payerContact", payerContact);
					// qkmap.put("payerIdType", payerIdType);
					// qkmap.put("payerId", payerId);
					// qkmap.put("payerIP", payerIP);
					qkmap.put("orderId", orderId);
					qkmap.put("orderAmount", orderAmount);
					qkmap.put("orderTime", orderTime);
					// qkmap.put("orderTimestamp", orderTimestamp);
					qkmap.put("productName", productName);
					qkmap.put("productNum", productNum);
					qkmap.put("productId", productId);
					qkmap.put("productDesc", productDesc);
					qkmap.put("ext1", ext1);
					qkmap.put("ext2", ext2);
					qkmap.put("payType", payType);
					qkmap.put("bankId", bankId);
					// qkmap.put("cardIssuer", cardIssuer);
					// qkmap.put("cardNum", cardNum);
					// qkmap.put("remitType", remitType);
					// qkmap.put("remitCode", remitCode);
					qkmap.put("redoFlag", redoFlag);
					qkmap.put("pid", pid);
					// qkmap.put("submitType", submitType);
					// qkmap.put("orderTimeOut", orderTimeOut);
					// qkmap.put("extDataType", extDataType);
					// qkmap.put("extDataContent", extDataContent);
					// qkmap.put("referDataType", remitType);
					// qkmap.put("referData", remitCode);
					// 构造HTML代码
					String htmlStr = CommonUtils.buildRequestHtml(qkmap, "post", "提交到快钱", QK_PAY_URL);
					System.out.println(htmlStr);
					log.info("快钱支付：：" + htmlStr);
					request.setAttribute("htmlStr", htmlStr);
					return "payapi";
					// res.setData(htmlStr);
					// res.setErrorCode(ErrorCode.SUCCESS);
				} else {
					log.info("memberId为" + payOrder.getCreateId() + "查无会员");
					
					res.setErrorCode(ErrorCode.ORDER_ERRPR);
					res.setMessage("memberId为" + payOrder.getCreateId() + "查无会员");
				}
			} else {
				log.info("payId为" + payId + "查询不到或者已支付");
				
				res.setErrorCode(ErrorCode.ORDER_ERRPR);
				res.setMessage("payId为" + payId + "查询不到或者已支付");
			}
		} else {
			
			res.setErrorCode(ErrorCode.ORDER_ERRPR);
			res.setMessage("payId为空");
		}
		return "";
	}
	
	@Valids({ @Valid(name = "payOrderVo.payType", required = true, regex = "ONLINE|CASH_DELIVERY"), @Valid(name = "payOrderVo.createMemberId", required = true),
			@Valid(name = "payOrderVo.device", required = true, regex = "WAP|PC"), @Valid(name = "payOrderVo.sysId", required = true),
			@Valid(name = "payOrderVo.orderSum", required = true, minValue = 0), @Valid(name = "payOrderVo.freightSum", required = true, minValue = 0),
			@Valid(name = "payOrderVo.useRedPacketId", required = false), @Valid(name = "payOrderVo.useRedPacketSum", required = false),
			@Valid(name = "payOrderVo.useJfSum", required = false), @Valid(name = "payOrderVo.discountJfMoney", required = false),
			@Valid(name = "payOrderVo.useStoreValue", required = false), @Valid(name = "payOrderVo.useRebateSum", required = false),
			@Valid(name = "payOrderVo.useCashBackSum", required = false), @Valid(name = "payOrderVo.totalWeight", required = true, minValue = 0),
			@Valid(name = "payOrderVo.isBrushOrder", required = true), @Valid(name = "payOrderVo.orderRemark", required = false),
			@Valid(name = "payOrderVo.receiptName", required = true), @Valid(name = "payOrderVo.productPaySum", required = true, minValue = 0.01),
			@Valid(name = "payOrderVo.memberId", required = false), @Valid(name = "payOrderVo.phone", required = true, regex = RegexUtils.MOBILE_FUZZY),
			@Valid(name = "payOrderVo.streetAddress", required = true), @Valid(name = "payOrderVo.address", required = true),
			@Valid(name = "payOrderVo.cityCode", required = true, minLength = 6, regex = "\\d{6}"),
			@Valid(name = "payOrderVo.countyCode", required = true, minLength = 6, regex = "\\d{6}"),
			@Valid(name = "payOrderVo.provinceCode", required = true, minLength = 6, regex = "\\d{6}"), @Valid(name = "payOrderVo.invoiceContent", required = true),
			@Valid(name = "payOrderVo.invoiceType", required = true, regex = "NOT_INVOICE|ELECTRONIC_INVOICE|ORDINARY_INVOICE|VTA_INVOICE"),
			@Valid(name = "payOrderVo.expressDeliveryName", required = true), @Valid(name = "payOrderVo.expressDeliveryCode", required = true),
			@Valid(name = "payOrderVo.orderDetails.proSku", required = true), @Valid(name = "payOrderVo.orderDetails.productNum", required = true, minValue = 0.0001),
			@Valid(name = "payOrderVo.orderDetails.productName", required = true), @Valid(name = "payOrderVo.orderDetails.productPrice", required = true, minValue = 0.01),
			@Valid(name = "payOrderVo.orderDetails.jfPrice", required = false), @Valid(name = "payOrderVo.orderDetails.productProperty", required = false),
			@Valid(name = "payOrderVo.orderDetails.purchasePrice", required = true, minValue = 0), @Valid(name = "payOrderVo.orderDetails.packNo", required = false),
			@Valid(name = "payOrderVo.orderDetails.useJfSum", required = false), @Valid(name = "payOrderVo.orderDetails.useRedPacketSum", required = false),
			@Valid(name = "payOrderVo.orderDetails.useCashBackSum", required = false), @Valid(name = "payOrderVo.orderDetails.packWeight", required = false),
			@Valid(name = "payOrderVo.orderDetails.premiums", required = true, regex = "CART_PREMIUM|NO_PREMIUM"),
			@Valid(name = "payOrderVo.orderDetails.supplierId", required = true), @Valid(name = "payOrderVo.orderDetails.subtotal", required = true, minValue = 0),
			@Valid(name = "payOrderVo.orderDetails.giveJfSum", required = false), @Valid(name = "payOrderVo.orderDetails.giveCashBackSum", required = false),
			@Valid(name = "payOrderVo.orderDetails.businessType", required = true, regex = "JOIN_SALES|SELF_SALES") })
	@ResponseBody
	@RequestMapping(value = "/submitPayOrder", method = RequestMethod.POST)
	@ApiOperation(notes = "创建付款单，主订单，订单详情", value = "创建付款单，主订单，订单详情")
	public Result submitPayOrder(@RequestBody PayOrderVo payOrderVo) throws ParseException, CustomException {
		Result result = new Result();
		result = payOrderService.submitPayOrder(payOrderVo);
		result.setErrorCode(ErrorCode.SUCCESS);
		
		return result;
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		// String s = "<form id=\"alipaysubmit\" name=\"alipaysubmit\" action=\"https://mapi.alipay.com/gateway.do?_input_charset=utf-8\" method=\"post\"><input type=\"hidden\" name=\"_input_charset\"
		// value=\"utf-8\"/><input type=\"hidden\" name=\"subject\" value=\"666666_0\"/><input type=\"hidden\" name=\"sign\"
		// value=\"zJA6yPOtkWgQlBfDmDXCeQSxXff36h5lUz44DRWf33YqTz27UzbxpfVH2EaHbrKyrLOYufjI2cSawEqNTUVYsH4LSFrdzE9DaIoVmtBhbqUZGnnM50hI1AO6VUhIBqytit0JF/DJJ8IlpvEjYML9O/dPkVBwkjgRvcTiAal1XZM=\"/><input
		// type=\"hidden\" name=\"notify_url\" value=\"http://123456\"/><input type=\"hidden\" name=\"body\" value=\"商品描述\"/><input type=\"hidden\" name=\"payment_type\" value=\"1\"/><input
		// type=\"hidden\" name=\"out_trade_no\" value=\"666666_0\"/><input type=\"hidden\" name=\"partner\" value=\"2088911156050662\"/><input type=\"hidden\" name=\"service\"
		// value=\"create_direct_pay_by_user\"/><input type=\"hidden\" name=\"total_fee\" value=\"0.01\"/><input type=\"hidden\" name=\"return_url\" value=\"http://123456\"/><input type=\"hidden\"
		// name=\"sign_type\" value=\"RSA\"/><input type=\"hidden\" name=\"seller_id\" value=\"2088911156050662\"/><input type=\"submit\" value=\"确认\"
		// style=\"display:none;\"></form><script>document.forms['alipaysubmit'].submit();</script>";
		// JSONObject.parseObject(s);
		System.out.println(yy(0));
		;
	}
	
	public static boolean yy(int j) {
		
		int i = 2;
		
		if (j < i) {
			yy(j + 1);
		} else {
			return true;
		}
		return false;
		
	}
	
	@RequestMapping(value = "/modityOrderStoreValue", method = RequestMethod.POST)
	@ApiOperation(notes = "修改订单是否使用充值" + "</br>返回码" + "</br>0-成功" + "</br>1001-参数异常" + "</br>1004-系统异常", value = "修改订单是否使用充值")
	@ResponseBody
	// @Valids({ @Valid(name = "useStoreValue", required = true, minValue = 0.01, maxValue = 9999999), })
	public Result<ModityOrderUseStore> modityOrderStoreValue(@ApiParam(name = "orderNo", value = "订单编码", required = true) @RequestParam(required = true) String orderNo,
			@ApiParam(name = "memberId", value = "会员ID", required = true) @RequestParam(required = true) Long memberId,
			@ApiParam(name = "sysId", value = "系统id", required = true) @RequestParam(required = true) Long sysId) throws CustomException {
		Result<ModityOrderUseStore> res = new Result<>();
		ModityOrderUseStore mo = payOrderService.modityOrderStoreValue(orderNo, sysId, memberId, null);
		res.setData(mo);
		res.setErrorCode(ErrorCode.SUCCESS);
		return res;
	}
	
}
